/**
 * 
 */
package com.tpl.core.basedata.service.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import com.tpl.core.basedata.dao.RoleDao;
import com.tpl.core.basedata.service.RoleService;
import com.tpl.core.common.DateUtil;
import com.tpl.core.common.page.ListPage;
import com.tpl.core.common.page.Page;
import com.tpl.core.dao.ExecuteSql;
import com.tpl.core.entity.sys.Role;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;



/**
 * @author 狄敏
 *
 * 创建时间：Jul 29, 2013 3:47:23 PM
 */
public class RoleServiceImpl implements RoleService {

	@Autowired
	private RoleDao roleDao;
	
	@Override
	public List<Role> getRoles(Long deptId) {
		List<Role> list = roleDao.getRolesByDeptId(deptId);
		return list;
	}

	@Override
	public void saveRole(Role role) {
		if(role.isTheDefault()){
			roleDao.updateAllDefaultZero(role.getDeptId());
		}
		roleDao.insertRole(role);
	}

	@Override
	public List<Role> getMenuByRoleId(Long roleId) {
		List<Role> list = roleDao.getMenusByRoleId(roleId);
		return list;
	}

	@Override
	public Page getRolePage(Long deptId, int pageIndex, int pageSize) {
		int count = roleDao.getRolesPageByDeptIdCount(deptId);
		if(count>0)
		{
			List<Role> list = roleDao.getRolesPageByDeptId(deptId,pageIndex, pageSize);
			return new ListPage(list, pageIndex, pageSize, count);
		}else
		{
			return new ListPage(new ArrayList<>(),count);
		}
	}

	@Override
	public List<Role> getRoleUserByParam(Long userId, Long roleId) {
		List<Role> list = null;
		if(userId != null){
			list = roleDao.getRoleUserByUserId(userId);
		}
		if(roleId != null){

			list = roleDao.getRoleUserByRoleId(roleId);

		}
		return list;
	}

	@Override
	public void saveRoleMenu(Long[] del_, Long[] new_, Long roleId) {
		//删除去掉的人员
		if(del_ != null && del_.length>0){
			for(int i=0;i<del_.length;i++){
				roleDao.deleteRoleMenuById(del_[i]);
			}
		}
		//保存新增的人员
		if(new_ != null && new_.length > 0){
			for(int i=0;i<new_.length;i++){
				Role role = new Role();
				role.setMenuId(new_[i]);
				role.setRoleId(roleId);
				roleDao.insertRoleMenu(role);
				
			}
		}
		
		
	}

	@Override
	public Role getRoleById(Long roleId) {
		Role role = roleDao.getRoleById(roleId);
		return role;
	}

	@Override
	public void update(Role role) {
		String sql = "update sys_role r set r.role_name=? ,r.updator=? ,r.update_date=?";
		String strUpdate ="";
		if(role.isBaseRole()) //判断是否基础角色如果是则添加
		{
			strUpdate += ", r.base_role = '1' ";
		}else{
			strUpdate += ", r.base_role = '0' ";

		}
		if(role.isTheDefault()) //判断是否默认如果默认则添加
		{
			strUpdate += ", r.is_default = '1' ";
			roleDao.updateAllDefaultZero(role.getDeptId());
		}else {
			strUpdate += ", r.is_default = '0' ";
		}
		strUpdate += " where r.id=?";
		sql += strUpdate;
		ExecuteSql.execute(sql, role.getRoleName(),role.getUpdator(), DateUtil.formatDateTime(role.getUpdateDate()),role.getId());
		
	}

	@Override
	public void delete(Long roleId) {
		doClearRoleUser(roleId,null); //删除所有
		String sql = "update sys_role r set r.deleted=1 where r.id=?";
		ExecuteSql.execute(sql, roleId);
	}

	@Override
	public void doClearRoleUser(Long roleId, Long userId) {
		String sql = "delete from sys_user_re_role where role_id=? "+(userId!=null?"and user_id !="+userId:""); 
		ExecuteSql.execute(sql, roleId);
	}
	/*@Override
	public void doClearRoleUser2(Long roleId, Long userId) {
		String sql = "delete from sys_role_re_menu where role_id=? "+(userId!=null?"and user_id !="+userId:""); 
		ExecuteSql.execute(sql, roleId);
	}*/
	@Override
	public void updateState(Long roleId, String state) {
		String sql ="update sys_role s set s.state=? where s.id";
		if("1".equals(state)){
			Role role=roleDao.getRoleById(roleId);
			ExecuteSql.execute(sql+"!=? and s.dept_id=?", 0,roleId,role.getDeptId());
		}
		ExecuteSql.execute(sql+"=?", state,roleId);
	}

	@Override
	public Long getUserNumByRoleId(Long roleId, Long userId) {
		String sql = "select count(1) from sys_user_re_role r where r.role_id=? and user_id!=?";
		Object obj = ExecuteSql.getSingleResult(sql, roleId,userId);
		return Long.parseLong(obj.toString());
	}

	@Override
	public List<Role> getRolesByMoreDeptId(String deptIds) {
		return roleDao.getRolesByMoreDeptId(deptIds);
	}

	@Override
	public void doReferRoles(Long deptId, List<Role> list,String creator) {
		List<Serializable[]> rms=null;
		Serializable[] rm=null;
		for(int i=0,count=list.size();i<count;i++){
			Role role=list.get(i);
			if(!role.isBaseRole()){
				Role oldRole = getRoleById(role.getId());
				role.setId(null);
				role.setCreateDate(DateTime.now().toDate());
				role.setCreator(creator);
				role.setDeptId(deptId);
				roleDao.insertRole(role);
				List<Role> menus = getMenuByRoleId(oldRole.getId());// 获取原权限的菜单
				rms = new ArrayList<Serializable[]>();
				for (Role menu : menus) {
					rm = new Serializable[2];
					rm[0] = Long.valueOf(role.getId());
					rm[1] = menu.getMenuId();
					rms.add(rm);
				}
				ExecuteSql.executeBatch("insert into SYS_ROLE_RE_MENU values (id,?,?)",rms.toArray(new Serializable[0][]));
			}else{
				role.setQuoteRoleId(role.getId());
				role.setId(null);
				role.setCreateDate(DateTime.now().toDate());
				role.setCreator(creator);
				role.setDeptId(deptId);
				roleDao.insertRole(role);
			}
		}
	}
	
	
	

}
